package com.zhuiYun.project.config.loginhandler;

import com.zhuiYun.project.common.errorCode.EmErrorCode;
import com.zhuiYun.project.common.response.CommonResult;
import com.zhuiYun.project.common.response.ResponseUtil;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName CustomizeAuthenticationFailureHandler
 * @Description 登录失败处理逻辑
 * @Author zcy
 * @Date 2023/3/27 11:48
 **/
@Component
public class CustomizeAuthenticationFailureHandler implements AuthenticationFailureHandler {
    /**
     *
     * 封装失败原因并返回
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
            CommonResult commonResult = null;
        if (e instanceof BadCredentialsException) {
            //密码错误
            commonResult= CommonResult.error(EmErrorCode.USER_PASSWORD_ERROR);
        }  else if (e instanceof UsernameNotFoundException) {
            //用户不存在
            commonResult = CommonResult.error(EmErrorCode.USER_NOT_EXIST);
        }else{
            //其他错误
            commonResult = CommonResult.error(EmErrorCode.USER_OTHER_ERROR);
        }
        ResponseUtil.responseJson(response,commonResult);
        }
}
